//
//  MentionsViewController.m
//  TuiTe
//
//  Created by 张 霄鹤 on 10-3-31.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "MentionsViewController.h"

#import "TwitterClient.h"
#import "Status.h"

#import "DataManager.h"

#import "ViewControllerChooser.h";


@implementation MentionsViewController

/*
 - (id)initWithStyle:(UITableViewStyle)style {
 // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 if (self = [super initWithStyle:style]) {
 }
 return self;
 }
 */

- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.navigationController.tabBarItem.title = @"Mentions";
	
	tweets = [[NSMutableArray alloc] init];
	
	// UIBarButtonItem *breload = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reload:)];
	breload = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reload:)];
	
	// self.navigationItem.leftBarButtonItem = breload;
	
	// [breload release];
	
	// UIBarButtonItem *bwrite = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(toWrite:)];
	
	bwrite = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(toWrite:)];
	
	// self.navigationItem.rightBarButtonItem = bwrite;
	
	// [bwrite release];
	
	NSArray *fobjs = (NSArray *)[DataManager loadObjectFromFile:@"mentions.dat"];
	
	if(fobjs && ([fobjs count] > 0)){
		NSInteger unlen = 0;
		NSInteger len = [fobjs count];
		[tweets addObjectsFromArray:fobjs];
		Status *tw = (Status *)[fobjs objectAtIndex:0];
		lastID = tw.tid;
		for(int i = 0;i<len;i++){
			tw = (Status *)[fobjs objectAtIndex:i];
			if(tw.unreaded){
				unlen++;
			}
		}
		if(unlen > 0){
			self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",unlen];
		}
	}
}



 - (void)viewWillAppear:(BOOL)animated {
	 [super viewWillAppear:animated];
	 self.tabBarController.navigationItem.title = @"Mentions";
	 self.tabBarController.navigationItem.leftBarButtonItem = breload;
	 self.tabBarController.navigationItem.rightBarButtonItem = bwrite;	 
 }

/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */

 - (void)viewWillDisappear:(BOOL)animated {
	 [super viewWillDisappear:animated];
	 self.tabBarController.navigationItem.leftBarButtonItem = nil;
	 self.tabBarController.navigationItem.rightBarButtonItem = nil;	
 }
 
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	[tweets removeAllObjects];
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	
	[DataManager saveObjectToFile:tweets withName:@"mentions.dat"];
	
	[tweets release];
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [tweets count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Set up the cell...
	NSInteger row = indexPath.row;
	Tweet *tt = [tweets objectAtIndex:row];
	if(tt){
		cell.textLabel.text = tt.text;
		cell.detailTextLabel.text = tt.usr.screen_name;
	}
	
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	NSInteger row = indexPath.row;
	Tweet *tw = [tweets objectAtIndex:row];
	if(tw){
		ViewControllerChooser *chooser = [ViewControllerChooser sharedChooser];
		TweetDetailViewController *td = (TweetDetailViewController *)[chooser choose:VC_DETAIL_TWEET];
		td.tweet = tw;
		td.tws = tweets;
		[self.navigationController pushViewController:td animated:YES];
	}
}



// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
		// [tweets removeObjectAtIndex:indexPath.row];
		NSInteger row = indexPath.row;
		[tweets removeObjectAtIndex:row];
		if(row==0){
			Tweet *td = [tweets objectAtIndex:0];
			if(td){
				lastID = td.tid;
			}
		}
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}



/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


- (void)reload:(id)sender{
	if(!loading){
		loading = YES;
		[NSThread detachNewThreadSelector:@selector(loadTweets:) toTarget:self withObject:nil];
	}	
}

- (void)loadTweets:(id)args{
	TwitterClient *tc = [TwitterClient getInstance];
	NSArray *ts = [tc doStatusesMentions:lastID];
	// NSArray *ts = [tc doStatusesPublicTimeLine];
	if(ts){
		NSInteger c = [ts count];
		if(c > 0){
			// self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",c];
			[self performSelectorOnMainThread:@selector(reloadTable:) withObject:ts waitUntilDone:NO];
		}else{
			// TODO 如果搜索结果为空 要展现给用户
		}
	}
	loading = NO;
}

- (void)reloadTable:(id)args{
	if(args){
		NSArray *ts = (NSArray *)args;
		NSInteger c = [ts count];
		NSString *bv = self.navigationController.tabBarItem.badgeValue;
		NSInteger ibv = [bv intValue];
		ibv += c;
		self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",ibv];
		// 插入数组到起始位置
		[tweets insertObjects:ts atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, c)]];
		[self.tableView reloadData];
	}
}

- (void)toWrite:(id)sender{
	// TODO 开启发送窗口
	ViewControllerChooser *chooser = [ViewControllerChooser sharedChooser];
	ReplyTweetViewController *rt = (ReplyTweetViewController *)[chooser choose:VC_REPLY_TWEET];
	rt.tweet = nil;
	rt.acType = AC_TYPE_WRITE;
	[self.navigationController pushViewController:rt animated:YES];
}


- (void)dealloc {
	[breload release];
	[bwrite release];
	[tweets release];
    [super dealloc];
}

@end

